#!/usr/bin/env node

const fs = require('fs').promises;
const path = require('path');
const { spawn } = require('child_process');

// FFmpeg路径
const FFMPEG_PATH = 'E:\\Words\\vsr\\resources\\backend\\ffmpeg\\win_x64\\ffmpeg.exe';

// 检查FFmpeg是否存在
async function checkFFmpeg() {
    try {
        await fs.access(FFMPEG_PATH);
        return true;
    } catch (err) {
        return false;
    }
}

// 递归查找所有wav文件
async function findAllWavFiles(dir) {
    let wavFiles = [];
    try {
        const files = await fs.readdir(dir);
        for (const file of files) {
            const filePath = path.join(dir, file);
            const stat = await fs.stat(filePath);
            
            if (stat.isDirectory()) {
                const subDirWavs = await findAllWavFiles(filePath);
                wavFiles = wavFiles.concat(subDirWavs);
            } else if (path.extname(file).toLowerCase() === '.wav') {
                wavFiles.push(filePath);
            }
        }
    } catch (err) {
        console.error(`Error reading directory ${dir}:`, err.message);
    }
    
    return wavFiles;
}

// 转换单个wav文件为mp3
function convertWavToMp3(inputPath, outputPath) {
    return new Promise((resolve, reject) => {
        const args = [
            '-i', inputPath,     // 输入文件
            '-codec:a', 'libmp3lame',  // 使用MP3音频编解码器
            '-b:a', '128k',      // 比特率128kbps
            '-y',                // 覆盖输出文件
            outputPath           // 输出文件
        ];
        
        console.log(`Converting: ${inputPath} -> ${outputPath}`);
        
        const ffmpeg = spawn(FFMPEG_PATH, args);
        
        ffmpeg.stdout.on('data', (data) => {
            console.log(`stdout: ${data}`);
        });
        
        ffmpeg.stderr.on('data', (data) => {
            // FFmpeg通常将进度信息输出到stderr
            console.log(`Processing: ${data}`);
        });
        
        ffmpeg.on('close', (code) => {
            if (code === 0) {
                console.log(`Successfully converted: ${inputPath}`);
                resolve();
            } else {
                console.error(`Failed to convert: ${inputPath} (exit code: ${code})`);
                reject(new Error(`Conversion failed with exit code: ${code}`));
            }
        });
        
        ffmpeg.on('error', (err) => {
            console.error(`Failed to start FFmpeg for ${inputPath}:`, err.message);
            reject(err);
        });
    });
}

// 主函数
async function main() {
    // 检查FFmpeg是否存在
    const ffmpegExists = await checkFFmpeg();
    if (!ffmpegExists) {
        console.error('Error: FFmpeg executable not found at', FFMPEG_PATH);
        process.exit(1);
    }
    
    // 获取resources/courses目录路径
    const coursesDir = path.join(__dirname, '../resources/word-pronunciation');
    
    // 检查目录是否存在
    try {
        await fs.access(coursesDir);
    } catch (err) {
        console.error('Error: Courses directory not found at', coursesDir);
        process.exit(1);
    }
    
    console.log('Searching for WAV files in:', coursesDir);
    
    // 查找所有wav文件
    const wavFiles = await findAllWavFiles(coursesDir);
    
    if (wavFiles.length === 0) {
        console.log('No WAV files found in the courses directory.');
        process.exit(0);
    }
    
    console.log(`Found ${wavFiles.length} WAV files to convert.`);
    
    // 转换所有wav文件
    let successCount = 0;
    let failCount = 0;
    
    for (const wavFile of wavFiles) {
        try {
            const mp3File = wavFile.replace(/\.wav$/i, '.mp3');
            await convertWavToMp3(wavFile, mp3File);
            successCount++;
        } catch (err) {
            console.error(`Error converting ${wavFile}:`, err.message);
            failCount++;
        }
    }
    
    console.log(`\nConversion complete!`);
    console.log(`Successfully converted: ${successCount}`);
    console.log(`Failed conversions: ${failCount}`);
    
    if (failCount > 0) {
        process.exit(1);
    }
}

// 执行主函数
main().catch(err => {
    console.error('Unexpected error:', err);
    process.exit(1);
});